import { API_CONFIG } from '../config/constants.js';

/**
 * 调用扣子平台聊天API
 * @param {string} content - 用户输入的文本内容
 * @returns {Promise} API响应结果
 */
export async function sendChatRequest(content) {
  try {
    const requestBody = {
      bot_id: API_CONFIG.BOT_CONFIG.bot_id,
      user_id: API_CONFIG.BOT_CONFIG.user_id,
      stream: API_CONFIG.BOT_CONFIG.stream,
      auto_save_history: API_CONFIG.BOT_CONFIG.auto_save_history,
      additional_messages: [
        {
          role: "user",
          content: content,
          content_type: "text"
        }
      ]
    };

    const response = await fetch(`${API_CONFIG.BASE_URL}/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': API_CONFIG.AUTHORIZATION_TOKEN
      },
      body: JSON.stringify(requestBody)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('API调用失败:', error);
    throw error;
  }
}

/**
 * 查询对话详情接口 - 检查状态
 * @param {string} chatId - 对话ID
 * @param {string} conversationId - 会话ID
 * @returns {Promise} API响应结果
 */
export async function retrieveChatStatus(chatId, conversationId) {
  try {
    const url = `${API_CONFIG.BASE_URL}/chat/retrieve?chat_id=${chatId}&conversation_id=${conversationId}`;

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': API_CONFIG.AUTHORIZATION_TOKEN
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('状态查询失败:', error);
    throw error;
  }
}

/**
 * 获取对话消息列表
 * @param {string} chatId - 对话ID
 * @param {string} conversationId - 会话ID
 * @returns {Promise} API响应结果
 */
export async function getChatMessages(chatId, conversationId) {
  try {
    const url = `${API_CONFIG.BASE_URL}/chat/message/list?chat_id=${chatId}&conversation_id=${conversationId}`;

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': API_CONFIG.AUTHORIZATION_TOKEN
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('消息获取失败:', error);
    throw error;
  }
}